import React, {Component} from "react";
import { Card, Image, Upload, Input, Form, message, Button } from 'antd'

import { foodDetails, updateFood,addFood } from '../../api/food'
class FoodDetails extends Component {
    myRef = React.createRef()
    state = {
        id: '',
        info: {
            fname: '',
            rid: '',
            practice: '',
            fpicture: ''
        },
        Look: true
    }
    componentDidMount () {
        const id = this.props.location.query ? this.props.location.query.id :  window.sessionStorage.getItem('id')
        if (id) {
            console.log(1)
            window.sessionStorage.setItem('id', id)
            const Look = window.sessionStorage.getItem('Look') || true
            this.setState({id, Look}, () => {
             this.getDetails()
         })
        } else {
            this.setState({Look: false})
        }
     }

     componentWillUnmount () {
        window.sessionStorage.setItem('id', '')
        window.sessionStorage.setItem('Look', true)
      }

     // 获取美食详情
     getDetails = async () => {
        const res = await foodDetails({fid: this.state.id})
        const info = res.data.data
        this.setState({info})
     }

     // 触发表单校验
     FormSubmit = () => {
        this.myRef.current.submit()
     }
    
     // 表单数据校验成功
     successData = (values) => {
        this.setState({info: {...this.state.info, ...values}}, () => {
            this.confrim()
           })
     }

     // 表单检验失败
     FormError = () => {
         message.error('数据错误，操作失败')
     }

     // 图片上传成功
     handleChange = (info) => {
        if (info.file.status !== 'uploading') {
        }
        if (info.file.status === 'done') {
            const fpicture = info.file.response.data.url
           this.setState({info: {...this.state.info, fpicture}})
          message.success('图片上传成功');
        } else if (info.file.status === 'error') {
          message.error('图片上传失败');
        }
      
      }

      // 更新数据
      updateData = async () => {
          console.log(this.state.info)
          const res = await updateFood(this.state.info)
          if (res.code === 200) {
            message.success('更新数据成功')
            this.getDetails()
            this.setState({Look: true})
        } else {
         message.error('更新数据失败')
        }
      }

      // 增加数据
      addData = async () => {
        const res = await addFood(this.state.info)
       if (res.code === 200) {
           message.success('更新数据成功')
           this.setState({Look: true})
           this.back()
       } else {
        message.error('更新数据失败')
       }
      
      }

      // 返回上一级
      back = () => {
          this.props.history.goBack()
      }

      // 编辑
      Edit = () => {
        this.setState({Look: false, fpicture: this.state.fpicture})
        window.sessionStorage.setItem('Look', false)
      }

      // 返回编辑
      backLook = () => {
          if (this.state.id) {
            this.setState({Look: true})
            window.sessionStorage.setItem('Look', true)
          } else {
              this.back()
              this.setState({Look: true})
              window.sessionStorage.setItem('Look', true)
          }
      
      }

      // 确认
      confrim = () => {
          if (this.state.id) {
              this.updateData()
          } else {
              this.addData()
          }
      }
      
    

  render() {
    const { info, Look } = this.state
    return (
        <div>
            {/* 编辑 */}
           
          {Look ? ( <Card style={{minHeight: '720px'}}>
              <div style={{display: 'flex', justifyContent: 'space-between'}}>
              <Button type="ghost" onClick={() => this.back()} className="backBtn">返回</Button>
              <Button className="editBtn"  onClick={() => {this.Edit()}}>编辑</Button>
              </div>
            <Form 
            ref={this.myRef} 
            onFinish={this.successData}
            onFinishFailed={this.FormError}>
                <div style={{display: 'flex'}}>
                <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>美食名称:</span>
                   <span className="textHd2">{info.fname}</span>
               </div>
               <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>店铺id:</span>
                   <span className="textHd2">{info.rid}</span>
               </div>
                </div>
                <div  style={{display: 'flex'}}>
                <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>食材:</span>
                   <span className="textHd2">{info.ingredients}</span>
               </div>
               <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>做法:</span>
                   <span className="textHd2">{info.practice}</span>
               </div>
                </div>
                <div  style={{display: 'flex', lineHeight: '72px'}}>
                <div style={{flex: 1 ,display: 'flex'}}>
                   <span style={{fontSize: '18px', fontWeight: 'bold'}}>美食链接:</span>
                   <span className="textHd2">{info.furl}</span>
               </div>
               <div style={{flex: 1, lineHeight: '72px',display: 'flex'}}>
                   <span  style={{fontSize: '18px', fontWeight: 'bold'}}>口味:</span>
                   <span className="textHd2">{info.flavor}</span>
               </div>
                </div>
                <div  style={{display: 'flex', lineHeight: '72px'}}>
                <div style={{flex: 1,  minHeight: '250px', alignItems: 'center', lineHeight: '72px',alignContent: 'center'}}>
                   <span style={{fontSize: '18px', fontWeight: 'bold'}}>图片</span>
                  <Image className="avater"  preview={false} src={info.fpicture} fallback=""></Image >
               </div>
               </div>
            </Form>
            </Card>) : (
               <Card style={{minHeight: '720px'}}>
                <Form 
                ref={this.myRef} 
                onFinish={this.successData}
                initialValues={info}
                onFinishFailed={this.FormError}>
                    <div style={{display: 'flex'}}>
                    <Form.Item label="美食名称" name="fname" rules={[{required: true,}]}   style={{flex: 1}}>
                       <Input style={{width: '320px'}} ></Input>
                   </Form.Item>
                   <Form.Item   label="店铺id" name="rid"   style={{flex: 1}} rules={[{required: true,}]}>
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item>
                    </div>
                    <div  style={{display: 'flex'}}>
                    <Form.Item  label="食材" name="ingredients"  style={{flex: 1}} rules={[{required: true,}]}>
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item>
                   <Form.Item   label="做法" name="practice" style={{flex: 1}} rules={[{required: true,}]}>
                       <Input  style={{width: '320px'}}></Input>
                   </Form.Item>
                    </div>
                    <div  style={{display: 'flex'}}>
                    <Form.Item  label="美食链接" name="furl"   style={{flex: 1}} rules={[{required: true,}]}>
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item>
                   <Form.Item  label="口味" name="flavor"   style={{flex: 1}} rules={[{required: true,}]}>
                       <Input  style={{width: '320px'}} ></Input>
                   </Form.Item>
                    </div>
                    <div  style={{display: 'flex'}}>
                    <Form.Item  label="图片" style={{flex: 1}}>
                      <Form.Item>
                      <Upload  action="http://111.75.252.147:8888/app/scenic/picUpload" name="file" onChange={(info) => this.handleChange(info)}  >
                            <Image className="avater"  preview={false} src={info.fpicture} fallback=""></Image >
                      </Upload> 
                      </Form.Item>
                   </Form.Item>
                    </div>
                </Form>
                <div style={{display: 'flex', justifyContent: 'flex-end'}}>
             <Button className="editBtn"  onClick={() => {this.FormSubmit()}}>确认</Button>
              <Button type="ghost" onClick={() => this.backLook()} className="backBtn" style={{marginLeft: '32px'}}>取消</Button>
              </div>
                </Card>
          )}
            
            {/* 查看 */}
        </div>
    );
  }
}

export default FoodDetails;